package com.sbhotel.chotellauncher.widget;

import android.app.Dialog;
import android.content.Context;
import android.graphics.PixelFormat;
import android.net.wifi.ScanResult;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.content.ContextCompat;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.sbhotel.chotellauncher.R;
import com.sbhotel.chotellauncher.constant.Constants;
import com.sbhotel.chotellauncher.util.SPUtil;
import com.sbhotel.chotellauncher.util.WifiUtil;

public class WifiPwdDialog extends Dialog implements View.OnClickListener {

    private String wifiName = "";
    ScanResult scanResult;
    TextView tvWifiName, tvConnectStatus, tvConnectWifi;
    View btnConnectWifi;
    EditText etvPwd;
    WifiUtil wiFiAdmin;

    public WifiPwdDialog(Context context, ScanResult result) {
        super(context);
        scanResult = result;
        this.wifiName = result.SSID;
        wiFiAdmin = new WifiUtil(getContext());
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.dialog_wifi_connect);

        initView();
        //initData();

        //按空白处不能取消动画
        setCanceledOnTouchOutside(false);
        //setCancelable(false);
        //设置window背景，默认的背景会有Padding值，不能全屏。当然不一定要是透明，你可以设置其他背景，替换默认的背景即可。
        //getWindow().setBackgroundDrawable(new ColorDrawable(ContextCompat.getColor(mContext, R.color.black_trans_90)));
        //一定要在setContentView之后调用，否则无效
        //getWindow().setLayout(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
        //getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ALERT);

        getWindow().getDecorView().setPadding(0, 0, 0, 0);
        getWindow().getDecorView().setBackground(ContextCompat.getDrawable(getContext(), R.mipmap.background));
        WindowManager.LayoutParams params = new WindowManager.LayoutParams(
                WindowManager.LayoutParams.WRAP_CONTENT,
                WindowManager.LayoutParams.WRAP_CONTENT,
                WindowManager.LayoutParams.TYPE_SYSTEM_ALERT,
                WindowManager.LayoutParams.FLAG_LAYOUT_IN_SCREEN,
                PixelFormat.TRANSLUCENT);

        getWindow().setAttributes(params);
    }

    private void initView() {
        tvWifiName = findViewById(R.id.tv_wifi_name);
        btnConnectWifi = findViewById(R.id.tv_connect_wifi);
        btnConnectWifi.setOnClickListener(this);
        tvConnectStatus = findViewById(R.id.tv_connect_status);
        tvConnectWifi = findViewById(R.id.tv_connect);
        etvPwd = findViewById(R.id.etv_wifi_pwd);
        if (!TextUtils.isEmpty(wifiName)) {
            tvWifiName.setText(wifiName);
        }
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.tv_connect_wifi:
                Log.d("leihuiming", "connect_wifi onClick");
                tvConnectStatus.setText(getContext().getText(R.string.connecting));
                btnConnectWifi.setEnabled(false);
                tvConnectWifi.setTextColor(ContextCompat.getColor(getContext(), R.color.power_off_border));
                connectWifi();
                break;
            default:
                break;
        }
    }

    private void connectWifi() {
        String pwd = etvPwd.getText().toString();
        Log.d("leihuiming", "pwd = " + pwd);

        if (!TextUtils.isEmpty(pwd)) {
            int netId = -1;
            Log.d("leihuiming", "scanResult.capabilities = " + scanResult.capabilities);
            Log.d("leihuiming", "scanResult.SSID = " + scanResult.SSID);
            if (scanResult.capabilities.contains("WEP")) {
                netId = wiFiAdmin.AddWifiConfig(null, scanResult.SSID, pwd, 2);
            } else if (scanResult.capabilities.contains("WPA2")) {
                netId = wiFiAdmin.AddWifiConfig(null, scanResult.SSID, pwd, 4);
            } else if (scanResult.capabilities.contains("WPA")) {
                netId = wiFiAdmin.AddWifiConfig(null, scanResult.SSID, pwd, 3);
            }
            Log.d("leihuiming", "netId = " + netId);
            if (netId != -1) {
                boolean resutl = wiFiAdmin.ConnectWifi(netId);
                if (resutl) {
                    tvConnectStatus.setText(getContext().getText(R.string.wifi_connect_success));
                    //Toast.makeText(getContext(), "连接成功", Toast.LENGTH_SHORT).show();
                    //mHandler.sendEmptyMessage(1); //更新倒计时
                } else {
                    tvConnectStatus.setText(getContext().getText(R.string.connect_error));
                    tvConnectWifi.setText("重新连接");
                    tvConnectWifi.setTextColor(ContextCompat.getColor(getContext(), R.color.set_wifi_color));
                    //Toast.makeText(getContext(), "网络连接错误", Toast.LENGTH_SHORT).show();
                }
            } else {
                tvConnectStatus.setText(getContext().getText(R.string.connect_error));
                //Toast.makeText(getContext(), "网络连接错误", Toast.LENGTH_SHORT).show();
                tvConnectWifi.setText("重新连接");
                tvConnectWifi.setTextColor(ContextCompat.getColor(getContext(), R.color.set_wifi_color));
            }
            btnConnectWifi.setEnabled(true);
        }
    }

    int countDown = 5;
    Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 1:
                    SPUtil.put(getContext(), Constants.SP_KEY_NET_ERROR, false);
                    Log.d("leihuiming", "pwd dialog put netError false");
                    if(countDown <= 0) {
                        if(isShowing()) {
                            dismiss();
                        }
                    } else {
                        tvConnectStatus.setText(String.format(getContext().getString(R.string.connect_success), countDown));
                        countDown--;
                        mHandler.sendEmptyMessageDelayed(1, 1000);
                    }
                    break;
                default:
                    break;
            }
        }
    };
}
